package com.iplatform.iplatformuser.privilege.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iplatform.commons.pagination.Pagination;
import com.iplatform.commons.utils.CommResponse;
import com.iplatform.commons.utils.UserUtil;
import com.iplatform.iplatformuser.common.CollectionUtil;
import com.iplatform.iplatformuser.function.resource.service.inter.IResurceService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriManagerService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriMenuService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriOrganizationService;
import com.iplatform.iplatformuser.privilege.service.inter.IPriRoleService;
import com.iplatform.module.privilege.PriManagerBean;
import com.iplatform.module.privilege.PriRoleBean;
import com.iplatform.module.privilege.dto.PriManagerDto;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * @author ld
 *
 */
@RestController
@RequestMapping("/api/v1/manager")
@Api(tags = "用户管理接口")
public class ApiManagerController {

	@Autowired
	private IPriManagerService userManagerService;

	@Autowired
	public IPriMenuService priMenuService;

	@Autowired
	public IPriOrganizationService priOrganizationService;

	@Autowired
	public IPriRoleService userRoleService;

	@Autowired
	public IResurceService resourceService;

//	@Value("${eureka.client.serviceUrl.defaultZone}")
//    public String eurekaPath;

	@Value("${spring.datasource.driver-class-name}")
	private  String dataSource;

	/**
	 * 用户列表
	 * @param formMap
	 * @param pagination
	 * @return
	 */
	@ApiOperation(value = "用户列表")
	@ApiImplicitParams({

			@ApiImplicitParam(dataType = "String", name = "mgrName", value = "模糊查询(用户名称和用户账号)", required = false, paramType = "query") })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@GetMapping(value = "list")
	public ResponseEntity<PageInfo<PriManagerDto>> list(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap,
														@ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {

		PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
		List<PriManagerDto> resultList = userManagerService.loadManagers(formMap);
		PageInfo<PriManagerDto> pageInfo = new PageInfo<PriManagerDto>(resultList);

		return new ResponseEntity<>(pageInfo, HttpStatus.OK);
	}

	/**
	 * 登陆时查询用户详情
	 * @param userCode
	 * @return
	 */
	@ApiOperation(value = "登陆时查询用户详情")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", name = "userCode", value = "用户登录名，必填，否则后端抛出异常", required = true, paramType = "path") })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@GetMapping(value = "/{userCode}")
	public ResponseEntity<PriManagerBean> getManager(@PathVariable(value = "userCode") String userCode) {
		PriManagerBean pri = new PriManagerBean();
		pri.setUserCode(userCode);

		//查询基本信息
		PriManagerBean priManagerBean = userManagerService.checkManager(pri);
		if("1".equals(priManagerBean.getIsSuper())) {
			//查询菜单信息
			Map<String, String> formMap = CollectionUtil.getHashMap(1);
			formMap.put("parentId", "0");
			formMap.put("status","1");
			priManagerBean.setPriMenuOpts(priMenuService.queryMenuByParentId(formMap));
		}else {
			//查询角色信息
			List<PriRoleBean> roleBeans = userRoleService.findRoleByMrgId(priManagerBean.getUserId());
			priManagerBean.setRoleBeans(roleBeans);

			//查询菜单信息
			Map<String, String> formMap = CollectionUtil.getHashMap(1);
			formMap.put("loginMgrId", priManagerBean.getUserId());
			priManagerBean.setPriMenuOpts(priMenuService.queryMenuListByLayer(formMap));
		}

		return new ResponseEntity<>(priManagerBean, HttpStatus.OK);
	}

	/**
	 * 用户详情
	 * @param userCode
	 * @return
	 */
	@ApiOperation(value = "用户详情(菜单角色)")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", name = "userCode", value = "用户登录名，必填，否则后端抛出异常", required = true, paramType = "path") })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@GetMapping(value = "/list/{userCode}")
	public ResponseEntity<PriManagerDto> list(@PathVariable(value = "userCode") String userCode) {
		Map<String, String> codeMap = CollectionUtil.getHashMap(1);
		codeMap.put("userCode", userCode);
		//查询基本信息
		PriManagerDto priManagerDto = userManagerService.loadManagers(codeMap).get(0);
		//查询主页
		//priManagerBean.setHomeUrl(userManagerService.queryHomeUrl(priManagerBean.getUserId()));
		/*//查询角色信息
		priManagerDto.setPriRoleBean(userRoleService.findRoleByMrgId(priManagerDto.getMgrId()));
		//查询菜单信息
		Map<String, String> formMap = CollectionUtil.getHashMap(1);
		formMap.put("loginMgrId", priManagerBean.getUserId());
		priManagerDto.setPriMenuOpts(priMenuService.queryMenuListByLayer(formMap));*/

		return new ResponseEntity<PriManagerDto>(priManagerDto, HttpStatus.OK);
	}

	/**
	 * 用户详情
	 * @param mgrId
	 * @return
	 */
	@ApiOperation(value = "用户详情(通过id)")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", name = "mgrId", value = "用户id", required = true) })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@GetMapping(value = "/details/{mgrId}")
	public ResponseEntity<PriManagerDto> details(@PathVariable(value = "mgrId") String mgrId) {
		PriManagerDto priManagerDto  = userManagerService.queryByMgrId(mgrId);
		return new ResponseEntity<PriManagerDto>(priManagerDto, HttpStatus.OK);
	}

	/**
	 * 新增用户
	 * @return
	 */
	@ApiOperation(value = "新增用户")
	@PostMapping()
	public ResponseEntity<CommResponse> add(PriManagerDto priManagerDto) {
		PriManagerBean pri = UserUtil.getLoginAppUser();

		Integer managerNum = userManagerService.checkAdd(priManagerDto.getUserCode());
		if (managerNum >= 1) {
			return new ResponseEntity<>( new CommResponse("账号重复",false),HttpStatus.BAD_REQUEST);
		}
		// TODO 获取当前用户
		if(StringUtils.isEmpty(priManagerDto.getRemark())) {
			priManagerDto.setRemark("");
		}
		if (StringUtils.isEmpty(priManagerDto.getStatus())){
			priManagerDto.setStatus("1");
		}
		if (StringUtils.isEmpty(priManagerDto.getIsSuper())){
			priManagerDto.setIsSuper("0");
		}
		if (StringUtils.isEmpty(priManagerDto.getVersion())){
			priManagerDto.setVersion(BigDecimal.valueOf(1));
		}
		if (StringUtils.isEmpty(priManagerDto.getMgrType())){
			priManagerDto.setMgrType("0");
		}

		if (pri != null){
			priManagerDto.setCreatedBy(pri.getUserCode());
		}else {
			priManagerDto.setCreatedBy("admin");
		}

		priManagerDto.setIsDeleted("N");
		priManagerDto.setStop("1");

		userManagerService.insert(priManagerDto);

		if (priManagerDto.getRoleIds().size() > 0){
			userManagerService.binds(priManagerDto.getMgrId(),priManagerDto.getRoleIds());
		}
		return new ResponseEntity<>( new CommResponse("添加成功",true),HttpStatus.CREATED);
	}


	/**
	 * 更新用户
	 *
	 * @return
	 */
	@ApiOperation(value = "更新用户")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@PutMapping()
	public ResponseEntity<CommResponse> update(PriManagerDto priManagerDto) {

		PriManagerBean pri = UserUtil.getLoginAppUser();
		Integer managerNum = userManagerService.checkUpdate(priManagerDto.getUserCode(),priManagerDto.getMgrId());
		if (managerNum >= 1) {
			return new ResponseEntity<>( new CommResponse("账号重复",false),HttpStatus.BAD_REQUEST);
		}
		if (pri != null){
			priManagerDto.setUpdatedBy(pri.getUserCode());
		}else {
			priManagerDto.setUpdatedBy("admin");
		}

		userManagerService.update(priManagerDto);

		return new ResponseEntity<>( new CommResponse("更新成功",true),HttpStatus.OK);
	}

	/**
	 * 删除用户
	 * @param deleteIds
	 * @return
	 */
	@ApiOperation(value = "删除用户")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", name = "deleteIds", value = "用户ID集合，逗号分隔",
					required = true, paramType = "query")})
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@PutMapping(value = "batchDel")
	public ResponseEntity<CommResponse> del(@RequestParam String deleteIds) {

		userManagerService.batchDeleteManager(deleteIds.split(","));

		return new ResponseEntity<>( new CommResponse("删除成功",true),HttpStatus.NO_CONTENT);
	}

	/**
	 * 更新用户状态
	 * @return
	 */
	@ApiOperation(value = "更新用户状态")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", name = "mgrId", value = "用户ID",
					required = true, paramType = "query") })
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
			@ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范") })
	@PutMapping(value = "/status")
	public ResponseEntity<CommResponse> updateStatus(@RequestParam String mgrId) {

		userManagerService.setStopOrActive(mgrId);

		return new ResponseEntity<>( new CommResponse("更新用户状态成功",true),HttpStatus.OK);
	}

	/**
	 * 查询角色名称和账号
	 * @return
	 */
	@ApiOperation(value = "查询角色名称和账号")
	@GetMapping(value = "/codeAndNameList")
	public ResponseEntity<JSONObject> codeAndNameList() {
		List<Map<String, String>> resultList = userManagerService.queryCodeAndName();

		JSONObject allObject = new JSONObject();
		JSONArray arrayCode = new JSONArray();
		JSONArray arrayName = new JSONArray();

		for(Map<String, String> data : resultList) {
			JSONObject objectCode = new JSONObject();
			JSONObject objectName = new JSONObject();
			objectCode.put("userCode", data.get("userCode"));
			objectName.put("userName", data.get("userName"));
			arrayCode.add(objectCode);
			arrayName.add(objectName);
		}

		allObject.put("code", arrayCode);
		allObject.put("name", arrayName);

		return new ResponseEntity<>(allObject, HttpStatus.OK);
	}


}
